package cc.yiueil.locks;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockMain {
    private final ReadWriteLock RW_LOCK = new ReentrantReadWriteLock();
    private final Lock R_LOCK = RW_LOCK.readLock();
    private final Lock W_LOCK = RW_LOCK.writeLock();
    private final int[] array = new int[10];
    public void inc(int index) {
        // 加写锁
        W_LOCK.lock();
        try {
            array[index] += 1;
        } finally {
            // 释放写锁
            W_LOCK.unlock();
        }
    }
    public int[] get() {
        // 加读锁
        R_LOCK.lock();
        try {
            return Arrays.copyOf(array, array.length);
        } finally {
            // 释放读锁
            R_LOCK.unlock();
        }
    }
}